﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AI_Tank.Client;
using AI_Tank.Game;
using System.IO;
using System.Collections.Specialized;
using MapDrawer.MapDrawer;
namespace AI_Tank
{
    public partial class MainDialog : Form
    {
        private const int ourID = 200;
        private const int roundInterval = 1000;

        public MainDialog()
        {
            InitializeComponent();
            //tring str = File.ReadAllText(@"C:\json.txt");
            //ParseLegStartData.GetMapData(str);
        }

        ServerConnector client1;


        private void button2_Click(object sender, EventArgs e)
        {
            client1 = ServerConnector.Connect("127.0.0.1", 6006);
            client1.OnReceiveData += Client1_OnReceiveData;
            client1.OnSocketException += Client1_OnSocketException; ;

            string sendData = $"00{Resource1.MindFlowRegist.Length}{Resource1.MindFlowRegist}";
            client1.Send(Encoding.UTF8.GetBytes(sendData));
        }


        private void Client1_OnSocketException(object sender, ServerConnectorEventArgs e)
        {
            client1.Close();
        }

        private List<MessageTypeAndContext> revcDataArray = new List<MessageTypeAndContext>();

        private class MessageTypeAndContext
        {
            private string msg;
            private string context;

            public MessageTypeAndContext(string msg, string context)
            {
                this.msg = msg;
                this.context = context;
            }

            public string Msg { get => msg; }
            public string Context { get => context; }
        }

        GameMapDrawer drawer;

        private void Client1_OnReceiveData(object sender, ServerConnectorEventArgs e)
        {
            string msg = e.Msg.Substring(5, e.Msg.Length - 5);
            string msgType = ServerMessageTypePaser.MessageTypeToString(ServerMessageTypePaser.Parse(msg));
            listView1.Invoke(new Action(() =>
            {
                listView1.Items.Add(listView1.Items.Count.ToString());
                listView1.Items[listView1.Items.Count - 1].SubItems.Add(msgType);
                listView1.Items[listView1.Items.Count - 1].SubItems.Add(msg.Length.ToString());
                revcDataArray.Add(new MessageTypeAndContext(msgType, msg));
                listView1.EnsureVisible(listView1.Items.Count - 1);
            }));
            if (ServerMessageTypePaser.StringToMessageType(msgType) == MessageType.Leg_start)
            {
                drawer = new GameMapDrawer(9999, DrawGameMap, roundInterval, 10);
                drawer.LegStart(ParseLegStartData.GetMapData(msg));
            }
            else if (ServerMessageTypePaser.StringToMessageType(msgType) == MessageType.Round)
            {
                if (drawer != null)
                    drawer.Round((new ParseRoundData(msg)).GetRoundDataObj());
            }
        }

        private Graphics imageGraphics; 
        private void DrawGameMap(Bitmap bitmap)
        {
            if (imageGraphics==null)
                imageGraphics = pictureBox1.CreateGraphics();
            imageGraphics.DrawImage(bitmap, 0, 0);
        }

        private void MainDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (client1 != null)
                client1.Close();
        }

        private void ShowData(MessageType messageType, string json)
        {
            switch (messageType)
            {
                case MessageType.Leg_start:
                    ShowLegStartData(json);
                    tabControl1.SelectedIndex = 0;
                    break;
                case MessageType.Round:
                    ShowRoundData(json);
                    tabControl1.SelectedIndex = 1;
                    break;
                case MessageType.Leg_end:
                    ShowLegEndData(json);
                    tabControl1.SelectedIndex = 2;
                    break;
                case MessageType.Game_over:
                    tabControl1.SelectedIndex = 3;
                    break;
                case MessageType.Nothing:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 显示子场开始信息
        /// </summary>
        private void ShowLegStartData(string json)
        {
            var result = ParseLegStartData.GetMapData(json);

            label19.Text = result.MapWidth.ToString();//宽度
            label18.Text = result.MapHeight.ToString();//高度

            string temp = "";
            //本方队伍信息
            if (result.TeamA_ID == ourID)
            {
                label21.Text = ourID.ToString();
                label24.Text = result.PlayerAs.Length.ToString();
                for (int i = 0; i < result.PlayerAs.Length; i++)
                {
                    if (i == 0)
                        temp = result.PlayerAs[i].ToString();
                    else
                        temp = temp + "," + result.PlayerAs[i].ToString();
                }
                label25.Text = temp;


                label30.Text = result.TeamB_ID.ToString();
                label27.Text = result.PlayerBs.Length.ToString();
                for (int i = 0; i < result.PlayerBs.Length; i++)
                {
                    if (i == 0)
                        temp = result.PlayerBs[i].ToString();
                    else
                        temp = temp + "," + result.PlayerBs[i].ToString();
                }
                label26.Text = temp;
            }
            else
            {
                label30.Text = ourID.ToString();
                label27.Text = result.PlayerAs.Length.ToString();
                for (int i = 0; i < result.PlayerAs.Length; i++)
                {
                    if (i == 0)
                        temp = result.PlayerAs[i].ToString();
                    else
                        temp = temp + "," + result.PlayerAs[i].ToString();
                }
                label26.Text = temp;


                label21.Text = result.TeamB_ID.ToString();
                label24.Text = result.PlayerBs.Length.ToString();
                for (int i = 0; i < result.PlayerBs.Length; i++)
                {
                    if (i == 0)
                        temp = result.PlayerBs[i].ToString();
                    else
                        temp = temp + "," + result.PlayerBs[i].ToString();
                }
                label25.Text = temp;
            }
        }

        private void DrawMap(Bitmap bitmap)
        {
            Invoke(new Action(() =>
            {
                pictureBox1.Image = bitmap;
            }));
        }


        /// <summary>
        /// 显示回合信息
        /// </summary>
        private void ShowRoundData(string json)
        {
            var result = (new ParseRoundData(json)).GetRoundDataObj();
            ShowBulletsInfo(result.Bullets);//子弹信息
            ShowMapElementInfo(result);     //地图元素信息
            ShowTeamsInfo(result.Teams);    //队伍信息

            //回合信息
            label40.Text = result.RoundID.ToString();

        }

        private void ShowBulletsInfo(List<Bullet> bullets)
        {
            listView2.BeginUpdate();
            listView2.Items.Clear();
            for (int i = 0; i < bullets.Count; i++)
            {
                listView2.Items.Add((i + 1).ToString());
                listView2.Items[i].SubItems.Add(bullets[i].TeamID.ToString());
                listView2.Items[i].SubItems.Add(Enum.GetName(typeof(BulletType), bullets[i].Type));
                listView2.Items[i].SubItems.Add($"({bullets[i].Position.X},{bullets[i].Position.Y})");
                switch (bullets[i].Direction)
                {
                    case Direction.Up:
                        listView2.Items[i].SubItems.Add("↑");
                        break;
                    case Direction.Right:
                        listView2.Items[i].SubItems.Add("→");
                        break;
                    case Direction.Down:
                        listView2.Items[i].SubItems.Add("↓");
                        break;
                    case Direction.Left:
                        listView2.Items[i].SubItems.Add("←");
                        break;
                    default:
                        break;
                }
            }
            listView2.EndUpdate();
        }

        private void ShowMapElementInfo(RoundData round)
        {
            listView3.BeginUpdate();
            listView3.Items.Clear();




            foreach (var item in round.Goods)
            {
                switch (item.ElementType)
                {
                    case ElementType.BrickWall:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("砖块");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y})");
                        break;
                    case ElementType.IronWall:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("铁块");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y})");
                        break;
                    case ElementType.River:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("河流");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y})");
                        break;
                    case ElementType.Coin:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("金块");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y}),coin = {((Coin)item).Point}");
                        break;
                    case ElementType.Star:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("超级子弹");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y})");
                        break;
                    case ElementType.Nothing:
                        listView3.Items.Add(listView3.Items.Count.ToString());
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add("无");
                        listView3.Items[listView3.Items.Count - 1].SubItems.Add($"({item.Position.X},{item.Position.Y})");
                        break;
                    default:
                        break;
                }
            }





            listView3.EndUpdate();
        }

        private void ShowTeamsInfo(List<Team> teams)
        {
            listView4.BeginUpdate();
            listView4.Items.Clear();
            for (int i = 0; i < teams.Count; i++)
            {
                listView4.Items.Add((i + 1).ToString());
                listView4.Items[i].SubItems.Add(teams[i].TeamID.ToString());
                listView4.Items[i].SubItems.Add(teams[i].Point.ToString());
                listView4.Items[i].SubItems.Add(teams[i].RemainLife.ToString());
            }
            listView4.EndUpdate();
        }

        /// <summary>
        /// 显示子场结束信息
        /// </summary>
        private void ShowLegEndData(string json)
        {
            var result = new ParseLegEndData(json).GetLegEndDataObj();
            foreach (var item in result.Teams)
            {
                if (item.Id == ourID)
                {
                    label48.Text = item.Id.ToString();
                    label45.Text = item.Point.ToString();
                }
                else
                {
                    label42.Text = item.Id.ToString();
                    label38.Text = item.Point.ToString();
                }
            }
        }

        private void MainDialog_Load(object sender, EventArgs e)
        {
            //隐藏标签
            tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top,
                                            tabPage1.Width, tabPage1.Height));



        }



        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
                return;
            int index = listView1.SelectedItems[0].Index;
            string type = listView1.SelectedItems[0].Text;


            ShowData(
           ServerMessageTypePaser.StringToMessageType(listView1.Items[index].SubItems[1].Text),
           revcDataArray[index].Context
           );


            textBox1.Text = revcDataArray[index].Context;
        }



    }
}
